﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PMatch;
using PMatch.Formats.SequenceSample;

namespace hmmeval
{
	class Program
	{
		static void Main(string[] args)
		{
			ExecSettings settings;
			ParseArguments(args, out settings);
			try
			{
				Execute(settings);
			}
			catch (Exception ex)
			{
				var eex = ex;
				do
				{
					Console.Error.WriteLine(ex.Message + "\n");
				} while ((eex = eex.InnerException) != null);
			}
		}

		private static void Execute(ExecSettings settings)
		{
			var model = MarkovModel.LoadFromFile(settings.Model);
			Console.WriteLine("HMM-classifier read");

			var ifile = samples.LoadFromFile(settings.DataSet);

			var positive = ifile.positive;
			var negative = ifile.negative;

			var pSampleCount = positive.Count();
			var nSampleCount = negative.Count();
			var totalSampleCount = pSampleCount + nSampleCount;

			Console.WriteLine("Input Positive: {0}", pSampleCount);
			Console.WriteLine("Input Negative: {0}", nSampleCount);
			Console.WriteLine("Input Total: {0}", totalSampleCount);

			var pWellMatch = positive.Count(x => model.Evaluate(new sample(x)));
			var nWellMatch = negative.Count(x => !model.Evaluate(new sample(x)));

			var pWellMatchPercentage = pWellMatch / (decimal)pSampleCount;
			var nWellMatchPercentage = nWellMatch / (decimal)nSampleCount;
			var wellMatch = pWellMatch + nWellMatch;
			var wellMatchPercentage = wellMatch / (decimal)totalSampleCount;

			Console.WriteLine("Positive-Well-Classified: {0} ({1:P2})", pWellMatch, pWellMatchPercentage);
			Console.WriteLine("Negative-Well-Classified: {0} ({1:P2})", nWellMatch, nWellMatchPercentage);
			Console.WriteLine("Well-Classified: {0} ({1:P2})", wellMatch, wellMatchPercentage);
		}

		private static void ParseArguments(string[] args, out ExecSettings settings)
		{
			if (args.Length < 2)
			{
				ShowUsage();
				Environment.Exit(255);
			}

			settings = new ExecSettings();
			settings.Model = args[0];
			settings.DataSet = args[1];
		}


		/// <summary>
		/// Muestra como se usa el programa por la consola
		/// </summary>
		private static void ShowUsage()
		{
			var help =
@"hmmtrain Trains a Hidden Markov Model based classifier
from a dataset containing positive and negative samples

	hmmeval model samples
 
	model: HMM-classifier Input file 
	samples: Samples input file	
";
			Console.WriteLine(help);
		}
	}

	class ExecSettings
	{
		public string Model { get; set; }
		public string DataSet { get; set; }
	}
}
